package com.yun.partnerSys.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.partnerSys.model.domain.User;
import com.yun.partnerSys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreRedisJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;


    //后期可以不写死
    //重点用户
    private List<Long> mainUser = Arrays.asList(2L);
    /* --------------------- todo  暂时不启用，与用户recommend冲突----------*/
    // todo cron语句记得自己改
   // @Scheduled(cron = "0 43 11  * * *")
    public void PreCacheJob(){

        RLock lock = redissonClient.getLock("yupao:precachejob:docache:lock");
        try {
            //如果获取锁成功
            if (lock.tryLock(0,30000L, TimeUnit.MILLISECONDS)) {
                System.out.println("----------------------获取成功！--------------");
                for(Long userId:mainUser){
                    String redisKey = String.format("yupao:user:recommend:%s", userId);

                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    //查询数据库分页展示
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);

                    //写缓存
                    try {
                        valueOperations.set(redisKey,userPage,60, TimeUnit.SECONDS);
                    }catch (Exception e){
                        log.error("redis set error",e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("PreCacheJob error",e);
        }finally {
            //判断是否为自己线程的锁
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }


    }
}
